// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-17 14:35
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.ArraysTrain;

import java.util.*;

@SuppressWarnings("ALL")
public class LongestWord {
    /**
     * 返回字典树中长度最长且字典序最小的单词1
     *
     * @param words
     * @return
     */
    public String longestWord(String[] words) {
        // 按照字符串长度进行升序排序
        HashSet<String> set = new HashSet<>();
        String ans = "";
        for (String word : words) {
            set.add(word);
        }
        for (String s : set) {
            int n = s.length(), m = ans.length();
            if (n < m) {
                continue;
            }
            // 当前字符串的长度和上一次结果长度相同，但是字典序小
            if (n == m && s.compareTo(ans) > 0) {
                continue;
            }
            boolean ok = true;
            for (int i = 1; i < n && ok; i++) {
                if (!set.contains(s.substring(0, i))) {
                    ok = false;
                }
            }
            if (ok) {
                ans = s;
            }

        }
        return ans;
    }
}
